<?php
/**
 * 商品
 * @date    2020-01-01
 * @author  kiro
 * @email   294843009@qq.com
 * @version 1.0
 */
namespace App\Http\Controllers\Api\V1;

use App\Models\Goods;
use App\Models\GoodsCategory;
use App\Models\Order;
use App\Models\SpeakCategory;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GoodsController extends ApiController
{
    // 商品列表
    public function list(Request $request)
    {
        $page = (int)$request->get('page', 1);
        $limit = (int)$request->get('limit', 10);
        $user_id = (int)$request->get('user_id');
        $offset = ($page - 1) * $limit;

        $total = Goods::where('status', 1)
            ->where(function ($query) use ($request, $user_id) {
                $user_id AND $query->where('user_id', $user_id);
                if ($request->type) {
                    if (is_array($request->type)) {
                        $query->whereIn('type', $request->type);
                    } else {
                        $query->where('type', $request->type);
                    }
                } else {
                    $query->whereIn('type', array_keys(Goods::$typeOptions));
                }
                $request->category_id and $query->where('category_id', $request->category_id);
                $request->speak_user_id and $query->where('speak_user_id', $request->speak_user_id);
                if ($request->is_speak) {
                    $query->where('speak_user_id', '>', 0);
                } elseif ($request->is_speak != ''){
                    $query->where('speak_user_id', 0);
                }
                $request->pay_status != '' AND $query->where('pay_status', $request->pay_status);
            })->count();
        $data = Goods::where('status', 1)
            ->where(function ($query) use ($request, $user_id) {
                $user_id AND $query->where('user_id', $user_id);
                if ($request->type) {
                    if (is_array($request->type)) {
                        $query->whereIn('type', $request->type);
                    } else {
                        $query->where('type', $request->type);
                    }
                } else {
                    $query->whereIn('type', array_keys(Goods::$typeOptions));
                }
                $request->category_id and $query->where('category_id', $request->category_id);
                $request->speak_user_id and $query->where('speak_user_id', $request->speak_user_id);
                if ($request->is_speak) {
                    $query->where('speak_user_id', '>', 0);
                } elseif ($request->is_speak != ''){
                    $query->where('speak_user_id', 0);
                }
                $request->pay_status != '' AND $query->where('pay_status', $request->pay_status);
            })
            ->offset($offset)
            ->limit($limit)
            ->orderBy('sort', 'ASC')
            ->orderBy('id', 'ASC')
            ->get();
        foreach ($data as &$value) {
            $value['goods_name'] = htmlspecialchars_decode($value['goods_name']);
            $value['content'] = htmlspecialchars_decode($value['content']);
            $value['company_intro'] = htmlspecialchars_decode($value['company_intro']);
            $value['desc'] = htmlspecialchars_decode($value['desc']);
            $value['thumb'] = dealUrl($value['thumb']);
            $value['company_icon'] = dealUrl($value['company_icon']);
            $images = array_filter(explode(',', $value['images']));
            foreach ($images as &$image) {
                $image = dealUrl($image);
            }
            $value['images'] = $images;
            $value['type_name'] = Goods::$typeOptions[$value['type']] ??'代言商品';
            if ($value['type'] == 99) {
                $value['category_name'] = SpeakCategory::getCategoryName($value['category_id']) ?? '';
            } else {
                $value['category_name'] = GoodsCategory::getCategoryName($value['category_id']) ?? '';
            }

            $value['company_tag'] = $value['company_tag'] ? explode(',', $value['company_tag']):[];
            $speak_user = null;
            if ($value['speak_user_id']) {
                $speak_user = User::where('id', $value['speak_user_id'])->first();
            }
            $value['speak_user'] = $speak_user;
        }
        return $this->success('成功', [
            'total' => $total,
            'total_page' => ceil($total / $limit),
            'current_page' => $page,
            'list' => $data
        ]);
    }

    // 商品详情
    public function view(Request $request)
    {
        if (empty($request->goods_id)) {
            return $this->error('商品ID不能为空');
        }
        $data = Goods::where('status', 1)
            ->where('id', $request->goods_id)
            ->first();
        if (empty($data)) {
            return $this->error('商品不存在');
        }
        $data['goods_name'] = htmlspecialchars_decode($data['goods_name']);
        $data['content'] = htmlspecialchars_decode($data['content']);
        $data['company_intro'] = htmlspecialchars_decode($data['company_intro']);
        $data['desc'] = htmlspecialchars_decode($data['desc']);
        $data['thumb'] = dealUrl($data['thumb']);
        $data['company_icon'] = dealUrl($data['company_icon']);
        $data['company_tag'] = $data['company_tag'] ? explode(',', $data['company_tag']):[];
        $images = array_filter(explode(',', $data['images']));
        foreach ($images as &$image) {
            $image = dealUrl($image);
        }
        $data['images'] = $images;
        $data['type_name'] = Goods::$typeOptions[$data['type']];
        Goods::where('id', $data['id'])->increment('view_num');
        return $this->success('成功', $data);
    }

    // 发布商品
    public function add(Request $request)
    {
        if (empty($this->getUserId())) {
            return $this->error('user_id不能为空');
        }
        $content = htmlspecialchars($request->get('content'));
        if (empty($request->type)) {
            return $this->error('type不能为空');
        }
        if (empty($request->goods_name)) {
            return $this->error('商品名称不能为空');
        }
        if (empty($request->thumb)) {
            return $this->error('预览图不能为空');
        }
        $model = new Goods();
        $model->user_id = $this->getUserId();
        $request->type AND $model->type = $request->type;
        $request->category_id AND $model->category_id = $request->category_id;
        $request->goods_name AND $model->goods_name = htmlspecialchars($request->goods_name);
        $request->is_company AND $model->is_company = $request->is_company;
        $request->company_short_name AND $model->company_short_name = $request->company_short_name;
        $request->company_name AND $model->company_name = $request->company_name;
        $request->company_person AND $model->company_person = $request->company_person;
        $request->company_icon AND $model->company_icon = $request->company_icon;
        $request->company_notice AND $model->company_notice = $request->company_notice;
        $request->company_phone AND $model->company_phone = $request->company_phone;
        $request->company_wechat AND $model->company_wechat = $request->company_wechat;
        $request->company_tag AND $model->company_tag = str_replace(['，', '|', ' '], [',', ',', ','], $request->company_tag);
        $request->company_intro AND $model->company_intro = htmlspecialchars($request->company_intro);
        $request->desc AND $model->desc = htmlspecialchars($request->desc);
        $request->thumb AND $model->thumb = $request->thumb;
        $request->price AND $model->price = $request->price;
        $request->s_price AND $model->s_price = $request->s_price;
        $request->s_day AND $model->s_day = $request->s_day;
        $request->amount AND $model->amount = $request->amount;
        $request->pay_type AND $model->pay_type = $request->pay_type;
        $request->pay_status AND $model->pay_status = $request->pay_status;
        $request->start_date AND $model->start_date = $request->start_date;
        $request->end_date AND $model->end_date = $request->end_date;
        $request->speak_user_id AND $model->speak_user_id = $request->speak_user_id;
        $content AND $model->content = $content;
        $request->open_type AND $model->open_type = $request->open_type;
        $request->out_url AND $model->out_url = $request->out_url;
        $request->buy_num AND $model->buy_num = $request->buy_num;
        $request->view_num AND $model->view_num = $request->view_num;
        $request->sort AND $model->sort = $request->sort;
        if (!empty($request->images) && count($request->images) && is_array($request->images)) {
            $model->images = implode(',', $request->images);
        }
        $model->status = 1;
        $result = $model->save();
        if (!$result) {
            return $this->error('发布失败');
        }
        return $this->success('发布成功', $model->id);
    }

    /**
     * 余额支付
     * @param Request $request
     */
    public function pay(Request $request)
    {
        $goods_id = $request->get('goods_id', 0);
        $pay_type = $request->get('pay_type') ?:'AMOUNT';
        if (empty($this->getUserId())) {
            return $this->error('请先登录');
        }
        if (empty($goods_id)) {
            return $this->error('goods_id不能为空');
        }

        if (!in_array($pay_type, array_keys(Order::$type_arr))) {
            return $this->error('支付方式不存在');
        }

        $goods = Goods::where('status', 1)->where('pay_status', 0)->where('id', $goods_id)->first();

        if (empty($goods)) {
            return $this->error('商品不存在');
        }

        if ($goods->pay_status == 1) {
            return $this->error('已支付');
        }

        DB::beginTransaction();
        try {

            $res = Goods::setStatus($goods_id, 1, $pay_type);
            if (!$res) {
                DB::rollBack();
                return $this->error('支付失败');
            }
            UserService::doAccount($this->getUserId(), -$goods->amount, '代言扣款', $pay_type, 'PAY_SPEAK');
            DB::commit();
            return $this->success('支付成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }
    }

    // 修改商品
    public function edit(Request $request)
    {
        if (empty($this->getUserId())) {
            return $this->error('user_id不能为空');
        }
        $goods_id = $request->get('goods_id');
        if (empty($goods_id)) {
            return $this->error('goods_id不能为空');
        }

        $content = htmlspecialchars($request->get('content'));

        $model = Goods::where('user_id', $this->getUserId())->where('id', $goods_id)->first();
        $request->type AND $model->type = $request->type;
        $request->category_id AND $model->category_id = $request->category_id;
        $request->goods_name AND $model->goods_name = htmlspecialchars($request->goods_name);
        $request->is_company AND $model->is_company = $request->is_company;
        $request->company_short_name AND $model->company_short_name = $request->company_short_name;
        $request->company_name AND $model->company_name = $request->company_name;
        $request->company_person AND $model->company_person = $request->company_person;
        $request->company_icon AND $model->company_icon = $request->company_icon;
        $request->company_notice AND $model->company_notice = $request->company_notice;
        $request->company_phone AND $model->company_phone = $request->company_phone;
        $request->company_wechat AND $model->company_wechat = $request->company_wechat;
        $request->company_tag AND $model->company_tag = str_replace(['，', '|', ' '], [',', ',', ','], $request->company_tag);
        $request->company_intro AND $model->company_intro = htmlspecialchars($request->company_intro);
        $request->desc AND $model->desc = htmlspecialchars($request->desc);
        $request->thumb AND $model->thumb = $request->thumb;
        $request->price AND $model->price = $request->price;
        $request->s_price AND $model->s_price = $request->s_price;
        $request->s_day AND $model->s_day = $request->s_day;
        $request->amount AND $model->amount = $request->amount;
        $request->pay_type AND $model->pay_type = $request->pay_type;
        $request->pay_status AND $model->pay_status = $request->pay_status;
        $request->start_date AND $model->start_date = $request->start_date;
        $request->end_date AND $model->end_date = $request->end_date;
        $request->speak_user_id AND $model->speak_user_id = $request->speak_user_id;
        $content AND $model->content = $content;
        $request->open_type AND $model->open_type = $request->open_type;
        $request->out_url AND $model->out_url = $request->out_url;
        $request->buy_num AND $model->buy_num = $request->buy_num;
        $request->view_num AND $model->view_num = $request->view_num;
        $request->sort AND $model->sort = $request->sort;
        if (!empty($request->images) && count($request->images) && is_array($request->images)) {
            $model->images = implode(',', $request->images);
        }
        $model->status = 1;
        $result = $model->save();
        if (!$result) {
            return $this->error('修改失败');
        }
        return $this->success('修改成功');
    }

    // 删除商品
    public function del(Request $request)
    {
        if (empty($request->id)) {
            return $this->error('商品id不能为空');
        }
        $info = Goods::find($request->id);
        if (empty($info)) {
            return $this->error('商品不存在');
        }
        if ($info->user_id != $this->getUserId()) {
            return $this->error('无权删除');
        }
        if ($info->status == 0) {
            return $this->error('商品已经删除');
        }
        $info->status = 0;
        $result = $info->save();
        if (!$result) {
            return $this->error('删除失败');
        }
        return $this->success('删除成功');
    }
}
